package com.ironman.mes.plugin.tcl.service;


import lombok.extern.slf4j.Slf4j;
import org.noear.dami.Dami;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.bean.LifecycleBean;

@Slf4j
@Component
public class DataHandler implements LifecycleBean {

    private static final String TOPIC_FILTER = "thing/up/property/hrged3ld/*";

    @Override
    public void start() throws Throwable {
        log.info("DataHandler start");
        Dami.<String, Void>bus().listen(TOPIC_FILTER, payload -> {
            String content = payload.getContent();
            ONode root = ONode.loadStr(content);
            String deviceCode = root.select("deviceCode").getString();
            double calorie = root.select("data.calorie").getDouble();
            int time = root.select("data.time").getInt();
            int distance = root.select("data.distance").getInt();
            int step = root.select("data.step").getInt();
            log.info("设备ID {}, 卡路里 {} ,运动时长 {} ,运动里程 {} ,累计步数 {}", deviceCode, calorie, time, distance, step);
        });
    }

    @Override
    public void preStop() throws Throwable {
        log.info("DataHandler preStop");
        Dami.<String, Void>bus().unlisten(TOPIC_FILTER);
    }
}
